import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
key = os.urandom(32)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('111.161.121.11', 19459))
print("已连接到服务器")
client_socket.send(key)
print("已发送密钥到服务器")
def encrypt_message(message):
    iv = os.urandom(AES.block_size)  # 随机生成 IV
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size))
    return iv + encrypted  # 返回 IV + 密文
def decrypt_message(encrypted_data):
    iv = encrypted_data[:AES.block_size]  # 提取 IV
    ciphertext = encrypted_data[AES.block_size:]  # 提取密文
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
    return decrypted.decode('utf-8')
try:
    while True:
        message = input("输入要发送的消息: ")
        encrypted_msg = encrypt_message(message)
        client_socket.send(encrypted_msg)
        encrypted_reply = client_socket.recv(1024)
        if not encrypted_reply:
            break
        decrypted_reply = decrypt_message(encrypted_reply)
        print(f"服务器回复: {decrypted_reply}")

except Exception as e:
    print(f"发生错误: {e}")
finally:
    client_socket.close()
    print("客户端已关闭")